/*                                                                                                                           
 * JFFS3 -- Journalling Flash File System, Version 3.                                                                        
 *                                                                                                                           
 * Copyright (C) 2006  Ferenc Havasi <havasi@inf.u-szeged.hu>,                                                               
 *                     Zoltan Sogor <weth@inf.u-szeged.hu>,                                                                  
 *                     Matyas Majzik <admin@newarcana.com>,                                                               
 *                     University of Szeged, Hungary                                                                         
 *
 * This software is distributed under the GNU GPL v2.
 * For licensing information, see the file 'LICENCE' in this directory.                                                             
 *                                                                                                                           
 */

/***************************************************************************
 *            sleep.c
 *
 *	precision delay routines
 ****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <sys/timeb.h>
#include "sleep.h"

long p_diff;
float p_corr;

void p_calibrate()
{
	struct timeb t1, t2;
	long t1l, t2l, tdiff;

	unsigned int i = 0;
	printf("calibrating precision timer, please wait...\n");
	ftime(&t1);
	do {
		i++;
	} while(i != 0xFFFFFFFFL);
	ftime(&t2);
	t1l = t1.time * 1000 + t1.millitm;
	t2l = t2.time * 1000 + t2.millitm;
	tdiff = t2l - t1l;
	printf("calibrate milisec: %li\n", tdiff);
	p_diff = tdiff;
	p_corr = 1000;
	ftime(&t1);
	p_sleep(1000000);
	ftime(&t2);	
	t1l = t1.time * 1000 + t1.millitm;
	t2l = t2.time * 1000 + t2.millitm;
	tdiff = t2l - t1l;
	printf("1 sec is really: %li msec\n", tdiff);
	p_corr = tdiff;
	printf("correction factor: %f\n", (double)1000 / (double)tdiff);
}

void p_sleep(unsigned long usec)
{
	unsigned int i;
	usec = usec * 1000 / p_corr;
	unsigned long w = 0xFFFFFFFFL / p_diff / 1000 * usec;
	i = 0;
	do {
		i++;
	} while(i != w);
}

/*
int main()
{
	struct timeb t1, t2;
	long t1l, t2l, tdiff;
	
	printf("calibrating...\n");
	p_calibrate();
	printf("waiting 1 sec...\n");
	ftime(&t1);
	p_sleep(1000000);
	ftime(&t2);
	printf("done.\n");
	t1l = t1.time * 1000 + t1.millitm;
	t2l = t2.time * 1000 + t2.millitm;
	tdiff = t2l - t1l;
	printf("1 sec is really: %i msec\n", tdiff);	
}*/
